#每条流的信息
import logging
from decimal import Decimal
import math
import numpy as np

logger_err = logging.getLogger(__name__)


class BasicFlow:
    # tint_k <= 1, 比例系数，去头去尾取中间的self.tint
    def __init__(self, packet, direct):
        self.id = packet.GetfwdFlowId()
        self.flowStartTime = packet.ts
        self.lastPktTime = packet.ts
        #self.FinCount = 0
        #self.FinDirect1 = -1
        #self.FinDirect2 = -1
        self.FinAck1 = -1
        self.FinAck2 = -1
        self.seqToackNum = dict()
        self.tint = []
        # self.tint_k = tint_k
        self.addfirstpacket(packet, direct)

    def getTint(self):
        if len(self.tint) == 0:
            return None
        else:
            # tints = sorted(self.tint)

            tints = self.tint
            
            # res_tints = [tint * 1000 for tint in tints if tint != 0.0]
            res_tints = [tint * 1000 for tint in tints if tint > 0.0]
            return res_tints
            

    def addfirstpacket(self, packet, direct):
        if direct == 1:
            if packet.IsSyn() or packet.IsSynAndAck():
                self.seqToackNum[packet.seqNum+1] = packet.ts
            elif packet.IsFin():
                self.FinAck1 = packet.seqNum+1
                self.seqToackNum[packet.seqNum+1] = packet.ts
            else:
                if packet.payloadlen != 0:
                    self.seqToackNum[packet.seqNum+packet.payloadlen] = packet.ts
        else:
            if packet.IsFin():
                self.FinAck1 = packet.seqNum+1

    def addpacket(self, packet, direct):
        self.lastPktTime = packet.ts
        if direct == 1:
            if packet.IsSynAndAck():
                self.seqToackNum[packet.seqNum+1] = packet.ts
            elif packet.IsFin():
                if self.FinAck1 != -1:
                    if self.FinAck1 != (packet.seqNum + 1):
                        self.FinAck2 = packet.seqNum + 1
                else:
                    self.FinAck1 = packet.seqNum + 1
                self.seqToackNum[packet.seqNum+1] = packet.ts
            else:
                if packet.payloadlen != 0:
                    self.seqToackNum[packet.seqNum+packet.payloadlen] = packet.ts
        else:
            if packet.IsFin():
                if self.FinAck1 != -1:
                    if self.FinAck1 != (packet.seqNum + 1):
                        self.FinAck2 = packet.seqNum + 1
                else:
                    self.FinAck1 = packet.seqNum + 1
            else:
                if self.seqToackNum.__contains__(packet.ackNum):
                    self.tint.append((Decimal(str(packet.ts))-Decimal(str(self.seqToackNum[packet.ackNum]))))
                    del self.seqToackNum[packet.ackNum]


